package com.maxafa.simpleimageprocessing;


import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainSurfaceView extends SurfaceView  implements SurfaceHolder.Callback, Runnable{

	private boolean m_is_running;
	private SurfaceHolder m_surfaceholder;
	private static int s_screen_width, s_screen_height;
	private Paint m_paint;
	private Thread m_mainthread;
	private Canvas m_lockcanvas;
	private float[] m_touch_x, m_touch_y;
	private int m_pointer_count;
	//read resource in asset folder
	private Bitmap m_bitmap_lauchericon, m_bitmap_lauchericon_scaled;
	private AssetManager m_assetmanager;
	private InputStream m_inputStream;
	private Matrix m_matrix;
	private double m_current_angle;
	
	
	public MainSurfaceView(Context context) {
		super(context);
		m_surfaceholder = getHolder();
		m_surfaceholder.addCallback(this);		
		setFocusable(true);
		s_screen_width = context.getResources().getDisplayMetrics().widthPixels;
		s_screen_height = context.getResources().getDisplayMetrics().heightPixels;
		m_assetmanager = context.getAssets();
	}

	private void Initialize(){
		m_paint = new Paint();		
		try{
			m_inputStream = m_assetmanager.open("images/photo.jpg");
			m_bitmap_lauchericon = BitmapFactory.decodeStream(m_inputStream);	
			m_bitmap_lauchericon_scaled = m_bitmap_lauchericon;
			m_inputStream.close();
		}catch(Exception e){
			m_inputStream = null;
			m_bitmap_lauchericon = null;
		}
		m_matrix = new Matrix();		
		m_matrix.postTranslate(-m_bitmap_lauchericon_scaled.getWidth()/2, -m_bitmap_lauchericon_scaled.getHeight()/2);//tranlate to center of image
		m_matrix.postRotate(0);// rotate image clock wise		
		m_matrix.postTranslate(s_screen_width/2, s_screen_height/2);		
		m_touch_x = new float[2];
		m_touch_y = new float[2];
		m_mainthread = new Thread(this);
		m_mainthread.start();
		m_is_running = true;
		
		
	}
	
	public void GamePause(){
		
	}
	
	public void GameResume(){
		
	}
	
	public void GameExit(){
		
	}
	
	private void GameUpdate(){
		
	}
	
	private void GameDraw(Canvas canvas){
		m_paint.setStrokeWidth(0);
		canvas.drawColor(Color.WHITE);
		canvas.drawText("Pointer count: " + m_pointer_count, 5, 15, m_paint);
		canvas.drawText("Pointer X1: " + m_touch_x[0], 5, 30, m_paint);
		canvas.drawText("Pointer Y1: " + m_touch_y[0], 5, 45, m_paint);
		canvas.drawText("Pointer X2: " + m_touch_x[1], 5, 60, m_paint);
		canvas.drawText("Pointer Y2: " + m_touch_y[1], 5, 75, m_paint);
		canvas.drawText("Angle: " + m_current_angle, 5, 90, m_paint);
		canvas.drawText("Angle atan2: " + Math.atan2((m_touch_x[0] - s_screen_width/2), (m_touch_y[0] - s_screen_height/2)), 5, 105, m_paint);
		canvas.drawText("New Width: " + (m_bitmap_lauchericon.getWidth() + m_bitmap_lauchericon.getWidth()*((((int)Math.abs(m_touch_x[1] - m_touch_x[0]) + (int)Math.abs(m_touch_y[1] - m_touch_y[0]))/2)/100)), 5, 120, m_paint);
		canvas.drawText("New Height: " + (m_bitmap_lauchericon.getHeight() + m_bitmap_lauchericon.getHeight()*((((int)Math.abs(m_touch_x[1] - m_touch_x[0]) + (int)Math.abs(m_touch_y[1] - m_touch_y[0]))/2)/100)), 5, 135, m_paint);
		canvas.drawText("Distance 1: " + (((int)Math.abs(m_touch_x[0] - s_screen_width/2) + (int)Math.abs(m_touch_y[0] - s_screen_height/2))/2), 5, 150, m_paint);
		
		
		//draw debug touch rect
//		m_paint.setStrokeWidth(3);
//		m_paint.setStyle(Paint.Style.STROKE);  
//		canvas.drawRect(m_touch_x[0], m_touch_y[0], m_touch_x[1], m_touch_y[1], m_paint);
//		canvas.drawBitmap(m_bitmap_lauchericon_scaled, s_screen_width/2 - m_bitmap_lauchericon_scaled.getWidth()/2, s_screen_height/2 - m_bitmap_lauchericon_scaled.getHeight()/2, m_paint);//draw scaled iamge with any size
		canvas.drawBitmap(m_bitmap_lauchericon_scaled, m_matrix, m_paint);//draw scaled iamge with any size
		
		
	}

	@Override
	public void run() {
		while(m_is_running){
			try{
				// Thread.sleep(20);
			}catch(Exception e){}
			GameUpdate();
			m_lockcanvas = m_surfaceholder.lockCanvas(null);
			synchronized (m_surfaceholder) {
				if(m_lockcanvas != null){
					GameDraw(m_lockcanvas);
					m_surfaceholder.unlockCanvasAndPost(m_lockcanvas);
				}
			}
		}		
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent e){
		super.onTouchEvent(e);
		m_pointer_count = e.getPointerCount();
		if(e.getActionMasked() == MotionEvent.ACTION_UP || e.getActionMasked() == MotionEvent.ACTION_POINTER_UP){			
			if(m_pointer_count == 1){
				m_pointer_count = 0;				
			}
		}
		if(e.getActionMasked() == MotionEvent.ACTION_DOWN || e.getActionMasked() == MotionEvent.ACTION_POINTER_DOWN){
			if(m_pointer_count > 1){
				m_touch_x[0] = e.getX(0);
				m_touch_y[0] = e.getY(0);
				m_touch_x[1] = e.getX(1);
				m_touch_y[1] = e.getY(1);
			}
		}
		if(e.getActionMasked() == MotionEvent.ACTION_MOVE){
			if(m_pointer_count > 1){
				m_touch_x[0] = e.getX(0);
				m_touch_y[0] = e.getY(0);
				m_touch_x[1] = e.getX(1);
				m_touch_y[1] = e.getY(1);			
                
//				m_bitmap_lauchericon_scaled = Bitmap.createScaledBitmap(m_bitmap_lauchericon, (int)Math.abs(m_touch_x[1] - m_touch_x[0]), (int)Math.abs(m_touch_y[1] - m_touch_y[0]), true);//scale any size
				m_bitmap_lauchericon_scaled = Bitmap.createScaledBitmap(m_bitmap_lauchericon, (int)(m_bitmap_lauchericon.getWidth() + m_bitmap_lauchericon.getWidth()*(((Math.abs(m_touch_x[0] - s_screen_width/2) + Math.abs(m_touch_y[0] - s_screen_height/2))/2)/100)), (int)(m_bitmap_lauchericon.getHeight() + m_bitmap_lauchericon.getHeight()*(((Math.abs(m_touch_x[1] - s_screen_width/2) + Math.abs(m_touch_y[1] - s_screen_height/2))/2)/100)), true);//scale zoom				
				
				m_matrix.reset();//reset the matrix
                m_matrix.postTranslate(-m_bitmap_lauchericon_scaled.getWidth()/2, -m_bitmap_lauchericon_scaled.getHeight()/2);//tranlate to center of image                
                m_current_angle = Math.toDegrees(Math.atan2((m_touch_x[0] - s_screen_width/2), (m_touch_y[0] - s_screen_height/2)));//roate image clock wise
                if(m_current_angle == 360)
                	m_current_angle = 0;
                m_matrix.postRotate((float)m_current_angle);// rotate image clock wise
                m_matrix.postTranslate(s_screen_width/2, s_screen_height/2);// draw image at the center of image in screen
			}else{
				if(m_pointer_count == 1){
					m_touch_x[0] = e.getX(0);
					m_touch_y[0] = e.getY(0);					
					m_matrix.reset();//reset the matrix
	                m_matrix.postTranslate(-m_bitmap_lauchericon_scaled.getWidth()/2, -m_bitmap_lauchericon_scaled.getHeight()/2);//tranlate to center of image                
	                m_current_angle = Math.toDegrees(Math.atan2((m_touch_x[0] - s_screen_width/2), (m_touch_y[0] - s_screen_height/2)));//roate image clock wise
	                if(m_current_angle == 360)
	                	m_current_angle = 0;
	                m_matrix.postRotate((float)m_current_angle);// rotate image clock wise
	                m_matrix.postTranslate(s_screen_width/2, s_screen_height/2);// draw image at the center of image in screen
				}else{				
					m_touch_x[0] = -1;
					m_touch_y[0] = -1;
					m_touch_x[1] = -1;
					m_touch_y[1] = -1;
				}
			}
		}
		return true;
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		Initialize();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		boolean retry = true;
		m_is_running = false;
        do {
            try {
                m_mainthread.join();
                retry = false;
            } catch (InterruptedException e) {
				e.printStackTrace();
                // we will try it again and again...
            }
        }while(retry);		
	}
}
